package fr.labri.macchiato.core.service;

import fr.labri.macchiato.core.api.Repository;
import fr.labri.macchiato.core.model.UserPreferences;

/**
 * Service for the {@link UserPreferences} class
 * 
 * @author Matthieu FOUCAULT
 * 
 */
public class PreferencesService {

	private Repository<UserPreferences, String> preferencesRepository;

	void setPreferencesRepository(
			Repository<UserPreferences, String> preferencesRepository) {
		this.preferencesRepository = preferencesRepository;
	}

	/**
	 * Creates a new PreferencesService, fetching entities from the given
	 * repository
	 * 
	 * @param preferencesRepository
	 */
	public PreferencesService(Repository<UserPreferences, String> preferencesRepository) {
		this.preferencesRepository = preferencesRepository;
		if (preferencesRepository.isEmpty()) {
			UserPreferences prefs = new UserPreferences();
			preferencesRepository.save(prefs);
		}
	}

	/**
	 * Sets the user preferences
	 * 
	 * @param preference
	 */
	public void setUserPreferences(UserPreferences preference) {
		preferencesRepository.save(preference);
		//System.out.println(Encoders.getInstance().getPreferencesEncoder().encode(preference));
	}

	/**
	 * 
	 * @return the stored user preferences
	 */
	public UserPreferences getUserPreferences() {
		return preferencesRepository.load(UserPreferences.PREFS_ID);
	}

	/**
	 * 
	 * @return true if the user has configured the application, false otherwise
	 */
	public boolean arePreferencesConfigured() {
		return getUserPreferences().getPreferencesConfigured();
	}

	/**
	 * Set to true if the user preferences have been configured
	 * 
	 * @param value
	 */
	public void setPreferencesConfigured(boolean value) {
		UserPreferences prefs = getUserPreferences();
		prefs.setPreferencesConfigured(value);
		setUserPreferences(prefs);
	}

	/**
	 * @return true if we have to use local storage, false otherwise
	 */
	public boolean getUseLocalStorage() {
		return getUserPreferences().getUseLocalStorage();
	}

}
